﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Collections;
using System.Windows;
using System.Windows.Shapes;
using System.Windows.Media;
using System.Windows.Ink;
using System.Windows.Controls;
using System.Windows.Threading;
using System.Diagnostics;




namespace TakeNote
{
    class Server
    {
        static int m_nEuckrCodepage = 51949;
        static System.Text.Encoding m_EUC_KR = System.Text.Encoding.GetEncoding(m_nEuckrCodepage);
        private Socket listener;
        public static ArrayList socketList = new ArrayList(); //서버에 연결된 소켓들의 Array 입니다.
        public  MainWindow WindowMain;
        public static MainWindow ff;
        private string m_sIPAddress;
      
        public Window2 window2 = null;
        public Window2 frm1 = new Window2();
       // public Frm1 frm2 = new Frm1();
       public Window4 win4 = new Window4();
       public Window1 win_sms = new Window1();
       // public Form1  frm1 = new ();
        public static double X;
        public static double Average_X;
        public static double Average_Y;

        public static int checkconnect = 0;


        public static double Y;
        public static double preX;
        public static double preY;
        public static double premX;
        public static double premY;
        public static int numReceived = 0;
        public static int clickflag = 0;
        public int flagsms = 0;
        public static int Transmission_File = 0;
        public static bool flag;
        private const int portNum = 7800;
        public static int Colorflag = 0;
        private Thread m_ThreadListen = null;
        private TcpListener m_TcpListener = null;
        
        public static Socket m_SocketServer = null;
        private Socket m_SocketServerFile = null;
        public static Socket acceptedSocket = null;

        private static Thread m_ThreadReceive = null;
        public delegate void ThisDelegate();   
        private string m_sServerIP;
        private int m_nServerPort;
        //   public void StrokeLine();
        public string ServerIP
        {
            get { return m_sServerIP; }
            set { m_sServerIP = value; }
        }

        public int ServerPort
        {
            get { return m_nServerPort; }
            set { m_nServerPort = value; }
        }
        public Server()
        {
        }

        public List<string> FileName = new List<string>();
        public List<int> FileSize = new List<int>();
        public List<string> underPathFiles = new List<string>();

        //   UdpClient newsock;

        public void StartSocket()
        {
            try
            {
                m_ThreadListen = new Thread(new ThreadStart(Listen));
                Console.WriteLine("asdasdasd");
                m_ThreadListen.Start();
                m_ThreadListen.IsBackground = true;
                WindowMain.SetText("서버가 시작되었습니as다.\r\n");

       //  frm1.Show();
    //    win4.Hide();
         

            }

            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }
        }

        //<-----------------udp받기 테스트-------------->
        public void Kill()
        {
           // Window2 w2 = new Window2();
            frm1.Close();                     //투명창닫기

            Process[] arryProgram = Process.GetProcesses();
            for (int i = 0; i < arryProgram.Length; i++)
            {
                if (arryProgram[i].ProcessName.Equals("POWERPNT"))
                {
                    arryProgram[i].Kill();      //프로세스 종료하기
                }
            }
        }


        private void ListenUDP()
        {
            int clickflag = 0;
            int counting = 0;
            int checksms = 0;
            try
            {

                //    Console.WriteLine("시ㅇㅇ작");
                byte[] buffer = new Byte[1000];


                string sHostName = "";
                sHostName = Dns.GetHostName();
                IPHostEntry ipHostEntry = Dns.GetHostByName(sHostName);
                IPAddress[] ipAddress = ipHostEntry.AddressList;    //  주소가져오기 현재것들을 가져오는거

                m_sIPAddress = ipAddress[0].ToString();     //주소가져오기
                //본인 IP
                EndPoint localEP = new IPEndPoint(IPAddress.Parse(m_sIPAddress), portNum);
                EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);

                Socket udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                udpSocket.Bind(localEP);
                // Console.WriteLine("asdasd");
                

                //Console.WriteLine("시ㅁㄴㅇ작");
                //SetSocketOption(SocketOptionLevel.Udp, SocketOptionName.ReceiveTimeout, 3000); 
                while (true)
                {
                    //flag = false;
                 //   Console.WriteLine(numReceived);
                    // preX = X;
                    // preY = Y;
                    numReceived = udpSocket.ReceiveFrom(buffer, ref remoteEP);

                   // Console.WriteLine("RmldRmld");
                   // flag = true;
                    //서버-클라이언트 간의 인코딩 통일(UTF8)
                    string s = Encoding.UTF8.GetString(buffer, 0, numReceived);
                   // Console.WriteLine(numReceived);

                    string[] sss = s.Split(new char[] { '/' });
                    // preX = System.Convert.ToDouble(sss[0]);
                    //preY = System.Convert.ToDouble(sss[1]);
                  //  Console.WriteLine("s[0] : " + sss[0]);
                  //  Console.WriteLine("s[1] : " + sss[1]);
                    if (sss[0] == "#")
                    {
                        if (sss[1] != "$")
                        {
                            if (sss[1] == "1")//드로잉시 값보정
                            {
                                //      Console.WriteLine("초기화 ");
                                frm1.mouseup();
                                preX = 0;
                                preY = 0;
                                X = 0;
                                Y = 0;
                                counting = 0;
                                clickflag = 1;

                            }
                            else if (sss[1] == "2") // 다음슬라이드
                            {

                                //-------애니메이션-----
                                /*
                                int a = WindowMain.ppt.SlideShowWindow.View.Slide.SlideNumber;
                                WindowMain.ppt.SlideShowWindow.View.Next();

                                int b = WindowMain.ppt.SlideShowWindow.View.Slide.SlideNumber;
                                if (a != b)
                                {
                                    WindowMain.ppt.SlideShowWindow.View.GotoSlide(a);
                                }
                                */
                                //-----------------------------------
                               // Console.WriteLine("테스트중4");
                                Console.WriteLine("피피티 바로넘기기 ");
                                // frm1.inkCanvas.Strokes.Clear();
                                //   Dispatcher.CurrentDispatcher.Invoke
                                int LastSlide = WindowMain.ppt.Slides.Count;
                                Console.WriteLine(LastSlide);
                                int a = WindowMain.ppt.SlideShowWindow.View.Slide.SlideNumber;
                                //if (a == LastSlide)
                                //{
                                 //   Console.WriteLine("마지막슬라이드임다");

                                //}
                                //else
                               // {

                                    frm1.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
                                      {
                                          frm1.canvas1.Strokes.Clear();
                                      }));
                                    int pagenumber = Convert.ToInt32(sss[2]);
                                    Console.WriteLine("들어온페이지번호 " + pagenumber);


                                    WindowMain.ppt.SlideShowWindow.View.GotoSlide(pagenumber+1);
                                //}
                            //    Console.WriteLine("before : " + a);
                                
    
                                preX = 0;
                                preY = 0;
                                X = 0;
                                Y = 0;
                                counting = 0;

                                // Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate { frm1.inkCanvas_Clear(); }));
                                //Dispatcher.CurrentDispatcher.Invoke((ThreadStart)delegate { frm1.inkCanvas.Strokes.Clear(); }, DispatcherPriority.Normal);


                            }
                            else if (sss[1] == "3")//이전슬라이드
                            {
                                Console.WriteLine("테스트중3");
                          
                                int a = WindowMain.ppt.SlideShowWindow.View.Slide.SlideNumber;
                                //if (a == 1)
                               // {
                               // }
                                //else
                               // {


                                    frm1.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
                                    {
                                        frm1.canvas1.Strokes.Clear();
                                    }));

                                    int pagenumber = Convert.ToInt32(sss[2]);
                                    Console.WriteLine("들어온페이지번호 " +pagenumber);
                                    WindowMain.ppt.SlideShowWindow.View.GotoSlide(pagenumber+1);
                                    //Console.WriteLine("피피티 바로이전 ");
                                    //WindowMain.ppt.SlideShowWindow.View.Previous();
                                    preX = 0;
                                    preY = 0;
                                    X = 0;
                                    Y = 0;
                                    counting = 0;
                              //  }
                                }
                            else if (sss[1] == "4")
                            {
                                frm1.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
                                {
                                    Colorflag = 0;
                                    frm1.canvas1.EditingMode = InkCanvasEditingMode.Ink;

                                }));


                            }
                            else if (sss[1] == "5")
                            {
                                frm1.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
                                {
                                    Colorflag = 1;
                                    frm1.canvas1.EditingMode = InkCanvasEditingMode.Ink;
                                    //       win4.Show();


                                }));

                            }
                            else if (sss[1] == "6")
                            {

                                frm1.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
                                {

                                    Colorflag = 2;
                                    frm1.canvas1.EditingMode = InkCanvasEditingMode.Ink;


                                }));
                                
                            }
                            else if (sss[1] == "7")
                            {
                                Console.WriteLine("오나");
                                frm1.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
                                {
                                    frm1.canvas1.EraserShape = new EllipseStylusShape(23, 23);
                                    frm1.canvas1.EditingMode = InkCanvasEditingMode.EraseByPoint;

                                }));
                            }
                            else if (sss[1] == "8")
                            {

                                frm1.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
                                {
                                    frm1.canvas1.Strokes.Clear();


                                }));

                            }
                            else if (sss[1] == "9")
                            {


                                frm1.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
                                {

                                    frm1.canvas1.EditingMode = InkCanvasEditingMode.Ink;

                                }));
                            }
                            else if (sss[1] == "a")
                            {
                                frm1.ChangeAlapha_false();

                            }
                            else if (sss[1] == "b")
                            {

                                frm1.ChangeAlapha_true();
                            }
                            else if (sss[1] == "c")
                            {


                                frm1.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
                                {
                                    if (flagsms == 1)
                                    {
                                        win_sms.Hide();

                                        flagsms--;
                                    }
                                    if (flagsms == 0)
                                    {
                                        win4.Show();
                                    }
                      
                                }));

                            }
                            else if (sss[1] == "d")
                            {
                                frm1.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
                                {
                                    win4.Hide();
                                }));
                            }
                            else if (sss[1] == "e")
                            {
                                //종료
                                // Environment.Exit(0);
                                //WindowMain.ppt.SlideShowWindow.Presentation();
                                //WindowMain.ppt1.Close();
                            }
                            else if (sss[1] == "f")
                            {
                                Console.WriteLine("테스트중1");
                                int a = WindowMain.ppt.SlideShowWindow.View.Slide.SlideNumber;
                        
                                WindowMain.ppt.SlideShowWindow.View.Next();
                                Console.WriteLine("테스트중");
                                int b = WindowMain.ppt.SlideShowWindow.View.Slide.SlideNumber;
                                if (a != b)
                                {
                                    WindowMain.ppt.SlideShowWindow.View.Previous();

                                }
                            }
                            else if (sss[1] == "g")
                            {
                                Console.WriteLine("테스트중2");
                                int a = WindowMain.ppt.SlideShowWindow.View.Slide.SlideNumber;
                                WindowMain.ppt.SlideShowWindow.View.Previous();
                                int b = WindowMain.ppt.SlideShowWindow.View.Slide.SlideNumber;
                                if (a != b)
                                {
                                    WindowMain.ppt.SlideShowWindow.View.Next();

                                }


                            }else if(sss[1] =="h") {
                                Console.WriteLine("종료 패킷 날라옴");
                                frm1.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
                                {
                                    Kill();
                                
                                
                                  }));
                            }
                            else if (sss[1] == "i")
                            {  
                                frm1.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
                               {

                                win_sms.Hide();
                               }));
                            }


                        }
                        else if (sss[1] == "$")
                        {
                            if (sss[2] == "1")
                            {

                                Console.WriteLine(sss[3]);
                                Console.WriteLine(sss[4]);
                                Console.WriteLine(sss[5]);


                                frm1.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
                                {
                                    win4.addcon(sss[3], sss[4], sss[5]);

                                }));
                            }
                            else if (sss[2] == "2")
                            {
                                Console.WriteLine("1번쨰");
                                Console.WriteLine(sss[3]);
                                Console.WriteLine(sss[4]);
                                Console.WriteLine(sss[5]);
                                //한문자메시지만 보는곳
                              if (flagsms == 0)
                                {
                                    Console.WriteLine("1번쨰");
                                    frm1.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
                                    {
                                        
                                        win_sms.AddSms(sss[3], sss[4], sss[5]);
                                        win4.Hide();
                                        win_sms.Show();

                                   //     flagsms++;
                                    }));
                                }
                                    /*
                                else if (flagsms == 1)
                                {

                                    Console.WriteLine("두번쨰");
                                    frm1.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
                                    {
                                        
                                    win_sms.Close();
                                    win_sms.AddSms(sss[3], sss[4], sss[5]);
                                    win_sms.Show();
                                    flagsms--;
                                     }));


                                }
                                     */
                            }
                        }

                    }else if (sss[0] != "#")
                    {                       double checkover =  System.Convert.ToDouble(sss[0]);
                                            double checkover1 = System.Convert.ToDouble(sss[1]);
                       Console.WriteLine("x값 : " + checkover);
                       Console.WriteLine("y값 : " + checkover1);
                if (checkover > 0 && checkover < 1)
                      {
                           if (counting == 0)
                           {   
                               
                               frm1.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
                               {
                                   if (flagsms == 1)
                                   {
                                       win_sms.Hide();

                                       flagsms--;
                                   }
                                  
                                   preX = System.Convert.ToDouble(sss[0]);
                                   preX = preX * frm1.Width;
                                   preY = System.Convert.ToDouble(sss[1]);
                                   preY = (preY *1.1)* frm1.Height;
                                
                                   counting++;

                               }));
                               
                               //--------------------------------------------------->
                           }else if(counting == 1){
                               frm1.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
                              {
                               premX = System.Convert.ToDouble(sss[0]);
                               premX = premX * frm1.Width;
                               premY = System.Convert.ToDouble(sss[1]);
                               premY = (premY * 1.1) * frm1.Height;

                               counting++;
                            }));
                           }
                           else if (counting == 2)
                           {
                      
                               

                               frm1.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
                               {
                                   X = System.Convert.ToDouble(sss[0]) * frm1.Width;
                                   Y = (System.Convert.ToDouble(sss[1])*1.1) * frm1.Height;
                                   Average_X = (X + preX + premX) / 3;
                                   Average_Y = (Y + preY +  premY) / 3;
                                   Console.WriteLine("평균값 : " + Average_X+ " :: " + Average_Y);
                                   
                                   Console.WriteLine(frm1.Width);
                                   Console.WriteLine(frm1.Height);
                             
                                       frm1.ink_draw_test2();
                                   
                                   //  frm1.ink_draw_test2();
                                     Console.WriteLine("X: " + X);
                                     Console.WriteLine("Y : " + Y);
                                   //   Console.WriteLine("preX : " + preX);
                                   //   Console.WriteLine("preY: " + preY);
                                     preX = premX;
                                     preY = premY;
                                   premX = X;
                                   premY = Y;


                               }));

                 


                           }
                       }
                    }
                    //    if (preX != 0) //초기값 보정
                    //  {

                    //
                    //   }


                    // Console.WriteLine("Y : " + Y);
                    // Console.WriteLine("preX : " + preX);
                    // Console.WriteLine("preY: " + preY);

                    //udpSocket.SendTo(buffer, numReceived, SocketFlags.None, remoteEP);
                   // numReceived = 0;
                    // Console.WriteLine("이건게속도나");
                    // Console.WriteLine(socketList.Count + "번째 컴퓨터 - " + acceptedIP + "에서 접속하였습니다.");
                }


                //WindowMain.FileOpenButtonIsEnabled(true);
                // Console.WriteLine("R끝");

            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }
        }



        //-------------------------------------------
        public void StartSockete()//파일전송까지 다되면 이거 호출
        {
            try
            {
                m_ThreadListen = new Thread(new ThreadStart(ListenUDP));
                m_ThreadListen.Start();
                m_ThreadListen.IsBackground = true;
                
                frm1.Topmost = true;
                frm1.Show();
                
               win4.Hide();


            }

            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }
        }



        private void Listen()
        {

            try
            {
                IPAddress ipAddress = IPAddress.Any;
                IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 17801);
                listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                listener.Bind(ipEndPoint);
                listener.Listen(10);
                // System.Windows.MessageBox.Show("연결을 기다립니다.");
                while (true)
                {
                    m_SocketServer = listener.Accept();      //  접속한 클라이언트 소켓
                    string acceptedIP = ((IPEndPoint)m_SocketServer.RemoteEndPoint).Address.ToString(); //  접속한 클라이언트 IP
                    socketList.Add(new SocketHandler(m_SocketServer));                                  //  접속리스트에 추가
                    Console.WriteLine("연결성공");
                    break;
                }
                //frm1.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
                //  {
                //     StartSockete();
                //}));

                Console.WriteLine("여기로나오나");
                WindowMain.FileOpenButtonIsEnabled(true);

            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }
            finally
            {
                Console.WriteLine("4444");
            }
        }


        public class SocketHandler
        {
            public Socket socket;
            public Thread threadHandler;



            public SocketHandler(Socket socket)
            {

                this.socket = socket;

                threadHandler = new Thread(new ThreadStart(Handler));
                threadHandler.Start();
            }
            public void Handler()                   //  실질적인 서버작업
            {
                byte[] buffer = new byte[500];
                int bufferCount;
                int counting = 0;
                Encoding src = Encoding.UTF8;
                Encoding dst = Encoding.Default;
                string strReceive;

                if (checkconnect == 1)
                {
                    socket = m_SocketServer.Accept();
                    Console.WriteLine("받을준비됨 : " + socket);

                    checkconnect = 0;
                }


                //   SendMsg((BroadcastServer.socketList.Count) + "명이 접속해 있습니다.");
                try
                {
                    while (true)
                    {


                        buffer.Initialize();

                        bufferCount = socket.Receive(buffer);
                        if (bufferCount == 0)
                        {
                            socket.Disconnect(true);
                            Console.WriteLine("연결이 끊어짐");
                            checkconnect = 1;
                         
                      //   socket = Server.Accept(n);
                            break;
                        }
                        
                        
                        Encoding.Convert(src, dst, buffer);

                        Console.WriteLine("111");
                        Console.Write(buffer);
                        Console.WriteLine("2222");
                        strReceive = dst.GetString(buffer);
                        Console.WriteLine(strReceive);
                        // string Msgs = ASCIIEncoding.UTF8.GetString(buffer);
                        //  Console.WriteLine(Msgs);
                        string[] result = strReceive.Split('\n');

                        //X = Convert.ToDouble(result[0]);
                        // Console.WriteLine(X);

                        /*
                        byte[] byteimsi = new byte[bufferCount];    // 남은버퍼 없애기용 임시byte
                        for (int i = 0; i < bufferCount; i++)
                        {
                            byteimsi[i] = buffer[i];
                        }
                        Msgs = ASCIIEncoding.UTF8.GetString(byteimsi);
                     */
                        //   Msgs = null;
                        //    System.Threading.Thread.Sleep(300);

                        if (counting == 0)
                        {
                            X = System.Convert.ToDouble(result[0]);
                            counting++;
                        }
                        else if (counting == 1)
                        {
                            Y = System.Convert.ToDouble(result[0]);
                            counting++;

                        }
                        else if (counting == 2)
                        {
                            preX = X;
                            X = System.Convert.ToDouble(result[0]);
                            counting++;
                        }
                        else if (counting == 3)
                        {
                            preY = Y;
                            Y = System.Convert.ToDouble(result[0]);
                            counting = 0;

                        }

                 
                        Console.WriteLine("X" + X + "  Y" + Y + "  preX" + preX + "  preY" + preY);
        
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("111111111111.");
                    Console.WriteLine(e.ToString());
                }
                finally
                {
                    Console.WriteLine("클라이언트가 종료하였습니다.");
                    //socket.Disconnect(true);
  
                   // socketList.Remove(this);

                  //  socket.Close();

                  //  socket = null;
                    
                }
            }



            public void SendMsg(string Msg)     //  메세지 보내기.
            {
                int bufferCount = 0;
                byte[] buffer = new byte[4096];
                buffer = ASCIIEncoding.UTF8.GetBytes(Msg);
                bufferCount = ASCIIEncoding.UTF8.GetByteCount(Msg);
                foreach (SocketHandler socketHandler in Server.socketList)
                {
                    socketHandler.socket.Send(buffer, 0, bufferCount, SocketFlags.None);
                }
            }
            public void end()
            {
                threadHandler.Abort();
            }
        }
        //private void ReceiveData()  //채팅받기
        //{
        //    try
        //    {
        //        byte[] bReceiveData = new byte[m_SocketServer.ReceiveBufferSize];
        //        while (true)
        //        {
        //            Array.Clear(bReceiveData, 0, bReceiveData.Length);
        //            // if (m_SocketServer.Receive(bReceiveData) > 0)
        //            //  {
        //            //     string[] sData = m_EUC_KR.GetString(bReceiveData).Split(':');
        //            // 
        //            //     if (sData[0].Equals("CHAT"))
        //            //     {
        //            //         WindowMain.SetText(sData[1] + "\r\n");
        //            //     }
        //            //     else if (sData[0].Equals("FILE"))
        //            //     {
        //            //     }
        //            // }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        System.Windows.MessageBox.Show(ex.Message);
        //    }
        //}90


        public void DoRunning()  //전송 쓰래드
        {
            try
            {
                Thread[] aThread = { new Thread(new ThreadStart(SendFile)) };
                foreach (Thread t in aThread)
                {
                    t.Start();
                }
            }
            catch (ThreadAbortException ex)
            {
                Thread.ResetAbort();
                System.Windows.MessageBox.Show(ex.Message);
            }
        }

       private void SendFile()   //파일 전송
        {
            try
            {
                List<string> sFileNames = new List<string>();
                //int pptcount = WindowMain.ppt1.Slides.Count;
                for (int i = 0; i < FileName.Count; i++)
                {

                    sFileNames.Add(FileName[i]);
                    int nStartIndex = 0;
                    int nSendSize = 4096;
                    int nSendDataLength = 0;
                    byte[] aaaa = new byte[30];

                    string[] sFileName = sFileNames[i].Split('\\');

                    string sendData1 = sFileName[sFileName.Length - 1]; //이름

                    int size1 = FileSize[i];
                    string fsize = Convert.ToString(size1); // 파일사이즈

                    //string pptfullcount = Convert.ToString(pptcount);

                    string currentpptcount = Convert.ToString(i + 1);
                    string fullpptcount = Convert.ToString(FileName.Count);


                    //string msg1 = fsize + "/" + sendData1;
                    string msg1 = sendData1 + "/" + fsize + "/" + currentpptcount + "/" + fullpptcount + "/";
                    //이름 /사이즈/현재번호/전체번호

                    Console.WriteLine(msg1);

                    aaaa = Encoding.UTF8.GetBytes(msg1);  //헤더파일 인코딩

                    //  string sendData = sFileName[sFileName.Length - 1] + ":" + FileSize[i];          //파일이름,크기 전송
                    //  byte[] bSendData = m_EUC_KR.GetBytes(sendData);   //bSendData 저장
                    // Console.WriteLine(aaaa);

                    int zzz = aaaa.GetLength(0);  //헤더파일 바이트 길이 
                    string qwr = Convert.ToString(zzz); //바이트 길이 , 스트링으로 변환
                    byte[] msg2 = new byte[5];  //버퍼선언
                    msg2 = Encoding.UTF8.GetBytes(qwr); //스트링으로 변환 된 값/
                    Console.WriteLine("ㅇㅇㅇ" + zzz);
                    // string msg2 = Encoding.UTF8.GetBytes(qwr);
                    // nSendDataLength = m_SocketServer.Send(msg2);

                    nSendDataLength = m_SocketServer.Send(msg2, 0, 2, 0);
                    Console.WriteLine("여긴되나");
                    nSendDataLength = m_SocketServer.Send(aaaa);
                    //소켓을통해 Send  //파일 명과 파일 크기를 접속된 클라이언트에게 먼저 전송한다.

                    Console.WriteLine("가나");


                //  Thread.Sleep(50);
                    byte[] bFileData = new byte[FileSize[i]];//파일사이즈만큼 바이트버퍼 할당

                    FileStream fs = File.Open(sFileNames[i], FileMode.OpenOrCreate);
                    fs.Read(bFileData, 0, FileSize[i]);   //파일스트림 데이터를 bFileData에 저장

                    if (BitConverter.IsLittleEndian)
                    {
                        //   Array.Reverse(bFileData);

                    }

                    fs.Close();

                    //Thread.Sleep(50);

                    while (nStartIndex < FileSize[i])
                    {
                        if (nStartIndex + nSendSize > FileSize[i])
                        {
                            nSendSize = FileSize[i] - nStartIndex;
                        }

                        nSendDataLength = m_SocketServer.Send(bFileData, nStartIndex, nSendSize, SocketFlags.None);

                        Console.WriteLine("보냄 : " + nSendDataLength);
                        nStartIndex += nSendDataLength;
                    }
                    Console.WriteLine("파일번호" + i);
                  //  Thread.Sleep(400);

                }
                FileName.Clear();
                FileSize.Clear();

                ///////////////////////////////////////////////////////////////
                Transmission_File = 1;


            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }
                    
        }




        public void StopSocket()
        {
            try
            {
                if (m_SocketServer != null)
                {
                    m_SocketServer.Close();
                    m_SocketServer = null;
                }

                if (m_SocketServerFile != null)
                {
                    m_SocketServerFile.Close();
                    m_SocketServerFile = null;
                }

                if (m_TcpListener != null)
                {
                    m_TcpListener.Stop();
                    m_TcpListener = null;
                }

                if (m_ThreadReceive != null)
                {
                    m_ThreadReceive.Abort();
                    m_ThreadReceive = null;
                }

                WindowMain.SetText("서버가 중지되었습니다.\r\n");
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }
        }

        public void CloseSocket()
        {
            try
            {
                if (m_SocketServer != null)
                {
                    m_SocketServer.Close();
                }

                if (m_ThreadListen != null)
                {
                    m_ThreadListen.Abort();
                }

                if (m_SocketServerFile != null)
                {
                    m_SocketServerFile.Close();
                }

                if (m_TcpListener != null)
                {
                    m_TcpListener.Stop();
                }

            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }
        }

    }
}